/**
 * @desc: 获取用户信息
 * @param {String} key 需要获取的子属性
 * @return {Object|String|Any}
 */
export const getUserInfo = (key?: string) => {
  let userInfo = localStorage.getItem('user')
  if (!userInfo) return ''
  userInfo = JSON.parse(userInfo)
  if (key && typeof key === 'string' && typeof userInfo === 'object' && userInfo) {
    return userInfo[key] || undefined
  }
  return userInfo
}


/**
 * @desc: 深拷贝
 * @param {Object} target 需要被拷贝的对象
 * @return {Object} 输出对象
 */
export function deepCopy<T extends Array<T> | any>(target: T): T {
  if (Array.isArray(target)) {
    return target.map((item) => deepCopy(item)) as T
  }
  const obj: T = {} as T
  for (const key in target) {
    if (typeof target[key] === 'object' && target[key] !== null) {
      obj[key] = deepCopy(target[key])
    } else {
      obj[key] = target[key]
    }
  }
  return obj
}

interface IFormat {
  [key: string]: any
}
export function parseTime(time: string | number, cFormat: string) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
      time = parseInt(time)
    }
    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj: IFormat = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
  }
  return format.replace(/{([ymdhisa])+}/g, (result, key: string) => {
    let value = formatObj[key]
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
}